package com.example.controller;

import com.example.exception.BusinessException;
import com.example.response.CommResponseEnum;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.rmi.NotBoundException;

/**
 * @program: springboot_course
 * @description:
 * @author: ChenZhiXiang
 * @create: 2019-06-13 17:19
 **/
@RestController
@Slf4j
public class HystrixController {

    @GetMapping(value = "/a")
    @HystrixCommand(
            fallbackMethod = "okFallback",
            threadPoolProperties = {  //10个核心线程池,超过20个的队列外的请求被拒绝; 当一切都是正常的时候，线程池一般仅会有1到2个线程激活来提供服务
                    @HystrixProperty(name = "coreSize", value = "10"),
                    @HystrixProperty(name = "maxQueueSize", value = "100"),
                    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "20")},
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"), //命令执行超时时间
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"), //若干10s一个窗口内失败三次, 则达到触发熔断的最少请求量
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000") //断路30s后尝试执行, 默认为5s
            })
    public String ok() throws Exception {
//        int l = new Random().nextInt(200);
//        log.info(String.format("l=%s", l));
//        TimeUnit.MILLISECONDS.sleep(l);
        int i = 0;
        if (i ==0){
            throw new BusinessException(CommResponseEnum.FAILURE1);
        }
        return "ok";
    }

    public String okFallback(Throwable e) {
        System.out.println("execute okFallback!" + e.getMessage());
        return "fallback";
    }
}
